using System;
using System.Collections.Generic;
using System.Text;

using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

using Microsoft.SharePoint;
using System.Web.UI.Adapters;
using Microsoft.SharePoint.Publishing.WebControls;
using Microsoft.SharePoint.Publishing.Fields;
using System.Web.UI.WebControls.WebParts;
using System.Text.RegularExpressions;
using Microsoft.SharePoint.WebControls;

namespace GetSharePointToValidate.Adapters
{
    public class GSPTV_RichHtmlField : ControlAdapter
    {
        protected override void Render(HtmlTextWriter writer)
        {
            if (this.Page is Microsoft.SharePoint.Publishing.PublishingLayoutPage && SPContext.Current.FormContext.FormMode.Equals(SPControlMode.Display))
            {
                RichHtmlField richHtml = this.Control as RichHtmlField;
                string outputHtml = string.Empty;                   
                if (richHtml.ItemFieldValue != null)
                {
                    string html = richHtml.ItemFieldValue.ToString();
                    Regex regExReplaceBR = new Regex("<br>", RegexOptions.IgnoreCase);
                    outputHtml = regExReplaceBR.Replace(html, "<br />");

                    Regex regEx = new Regex("([a-zA-Z]+)=([^\"\\s>]+)(\\s|>)", RegexOptions.IgnoreCase);
                    MatchCollection matchCollection = regEx.Matches(outputHtml);
                    outputHtml = regEx.Replace(outputHtml, "$1=\"$2\"$3");

                    Regex regExImage = new Regex("<img([^>]*[^/])>", RegexOptions.IgnoreCase);
                    MatchCollection matchCollectionImage = regExImage.Matches(outputHtml);
                    outputHtml = regExImage.Replace(outputHtml, "<img $1 />");

                    Regex regExReplaceBorder = new Regex("border=\"[0-9]\"", RegexOptions.IgnoreCase);
                    outputHtml = regExReplaceBorder.Replace(outputHtml, "");
                }
                writer.Write(outputHtml);
            }
            else
            {
                base.Render(writer);
            }
        }
    }
}
